package cn.bonoon.controllers.holidays;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.HolidayService;
import cn.bonoon.entities.plugins.HolidayEntity;
import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.AbstractPanelController;
import cn.bonoon.kernel.web.models.JsonResult;

@Controller
@RequestMapping("s/sys/holiday")
public class HolidayController extends AbstractPanelController {

	private HolidayService holidayService;

	@Autowired
	public HolidayController(HolidayService holidayService) {
		this.holidayService = holidayService;
	}

	@Override
	protected void onLoad(PanelEvent event) throws Exception {
		Integer year = Calendar.getInstance().get(Calendar.YEAR);
//		event.getModel().addObject("year", year);
		event.getModel().addObject("content", content(tbody(year), year));
		event.setVmPath("sys/holiday/holiday-index");
	}

	@ResponseBody
	@RequestMapping(value = "!{mid}/year/flush", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult create(@PathVariable("mid") String mid, Integer year, Model model) {
		if (null == year || year < 2000) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		String content = content(tbody(year), year);
//		model.addAttribute("year", year);
		model.addAttribute("content", content);
		return JsonResult.result(content);
	}

	@ResponseBody
	@RequestMapping(value = "!{mid}/save", method = RequestMethod.POST)
	public JsonResult save(@PathVariable("mid") String mid, HttpServletRequest request, HolidayEditor editor) {
		try {
//			OperateEvent event = new OperateEvent(applicationContext, mid, request, null, getUser());
//			event.setScope(VisibleScope.DOMAIN);
			HolidayEntity entity = holidayService.getYear(editor.getYear());
			if (null == entity) {
				entity = new HolidayEntity();
				entity.setCreateAt(new Date());
				entity.setCreatorId(getUser().getId());
				entity.setCreatorName(getUsername());
				holidayService.save(build(entity, editor));
			} else {
				entity.setUpdateAt(new Date());
				entity.setUpdaterId(getUser().getId());
				entity.setUpdaterName(getUsername());
				holidayService.update(build(entity, editor));
			}
			return JsonResult.result();
		} catch (Exception e) {
			log.error("节假日定义异常！", e);
			return JsonResult.result(e);
		}
	}

	private HolidayEntity build(HolidayEntity entity, HolidayEditor editor) {
		entity.setYear(editor.getYear());
		List<String> months = editor.getMonths();
		entity.setJanuary(months.get(0));
		entity.setFebruary(months.get(1));
		entity.setMarch(months.get(2));
		entity.setApril(months.get(3));
		entity.setMay(months.get(4));
		entity.setJune(months.get(5));
		entity.setJuly(months.get(6));
		entity.setAugust(months.get(7));
		entity.setSeptember(months.get(8));
		entity.setOctober(months.get(9));
		entity.setNovember(months.get(10));
		entity.setDecember(months.get(11));
		return entity;
	}

	public String tbody(int year) {
		HolidayEntity holiday = holidayService.getYear(year);
		String[] months = new String[12];
		if (null != holiday) {
			months[0] = holiday.getJanuary();
			months[1] = holiday.getFebruary();
			months[2] = holiday.getMarch();
			months[3] = holiday.getApril();
			months[4] = holiday.getMay();
			months[5] = holiday.getJune();
			months[6] = holiday.getJuly();
			months[7] = holiday.getAugust();
			months[8] = holiday.getSeptember();
			months[9] = holiday.getOctober();
			months[10] = holiday.getNovember();
			months[11] = holiday.getDecember();
		}

		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		StringBuilder items = new StringBuilder();

		for (int i = 0; i < months.length; i++) {
			c.set(Calendar.MONTH, i);
			int day_count = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 当前月的天数
			int week_of_minday = week_of_minday(year, i + 1); // 当前月第一天是星期几
			items.append("<tr><th style='text-align:center;' rowspan='2'>");
			items.append(format_month(i));
			items.append("</th>");
			for (int k = 1; k < week_of_minday; k++) {
				items.append("<td></td>");
			}
			int week = week_of_minday;
			int br = 0;

			String m = months[i];
			int[] holidays = null;
			int holidays_len = 0;
			int index = 0;
			if (StringHelper.isNotEmpty(m)) {
				holidays = StringHelper.tointArray(m);
				holidays_len = holidays.length;
			}

			for (int j = 1; j <= day_count; j++) {
				if (null != holidays) {
					if (index < holidays_len && holidays[index] == j) {
						items.append("<td style='text-align:center;' class='day selectedDay'>");
						index++;
					} else {
						items.append("<td style='text-align:center;' class='day'>");
					}
				} else {
					if (week == 1 || week == 7) {
						items.append("<td style='text-align:center;' class='day selectedDay'>");
					} else {
						items.append("<td style='text-align:center;' class='day'>");
					}
				}
				items.append("<input type='hidden' class='month").append(i).append("' value='").append(j).append("' />");
				items.append(j).append("</td>");

				if (week == 7) {
					if (++br == 3) {
						br = 0;
						items.append("</tr><tr>\n");
					} else {
						items.append("<td style='background:#ededed;'></td>");
					}
				}

				if (++week > 7) {
					week = 1;
				}
			}

			week = --week < 1 ? 7 : week; // 当月最后一天的星期
			int colspan = 23 - (week == 7 ? br * 8 : br * 8 + week);
			items.append("<td colspan='" + colspan + "'></td>");

			items.append("</tr>");
		}
		return items.toString();
	}

	public String content(String tbody, int year) {
		StringBuilder content = new StringBuilder();
		content.append("<tr style=''>");
		content.append("<td colspan='24' style='text-align:center;padding:15px 0 15px 0;'>请选择年份：");
		content.append("<select style='width:100px;'  name='sel_year' id='sel_year'>");
		int current_year = Calendar.getInstance().get(Calendar.YEAR);
		for (int i = current_year; i < (current_year + 10); i++) {
			if (i == year) {
				content.append("<option value='" + i + "' selected='selected'  >" + i + "</option>");
			} else {
				content.append("<option value='" + i + "'>" + i + "</option>");
			}
		}
		content.append("</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		content.append("<strong><span style='font-size:16px;'><span id='title_year' name='title_year'>" + year
				+ "</span>年节假日</span></strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注：列表中有图标表示为休息日，可以用鼠标点击设置。</td>");
		content.append("</tr>");
		content.append("<tr>");
		content.append("<th style='width:70px;text-align:center;'>月份/星期</th>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("<td style='width:2px;background:#ededed;'></td>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("<td style='width:2px;background:#ededed;'></td>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("</tr>");
		content.append(tbody);
		return content.toString();
	}

	// 获取某年某月的第一天是星期几（return 1-日，2-星期一，...，7-星期六）
	private int week_of_minday(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	private String format_month(int num) {
		String[] months = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" };
		return months[num];
	}

}
